/*
 * @lc app=leetcode.cn id=40 lang=cpp
 *
 * [40] 组合总和 II
 */

// @lc code=start
class Solution
{
private:
    vector<vector<int>> res;
    vector<int> path;
    void backtracking(vector<int> &candidates, int target, int startIndex, vector<bool> &used)
    {
        if (target == 0)
        {
            res.push_back(path);
            return;
        }
        for (int i = 0; i < candidates.size() && target - candidates[i] >= 0; i++)
        {
            //避免重复
            if (i > 0 && candidates[i] == candidates[i - 1] && used[i - 1] == false)
            {
                //同一层两个相同元素直接跳过
                continue;
            }
            path.push_back(candidates[i]);
            used[i] = true;
            backtracking(candidates, target - candidates[i], i + 1); // i+1元素不重复
            used[i] = false;
            path.pop_back();
        }
    }

public:
    vector<vector<int>> combinationSum2(vector<int> &candidates, int target)
    {
        vector<bool> used(candidates.size(), false);
        sort(candidates.begin(), candidates.end());
        backtracking(candidates, target, 0, used);
        return res;
    }
};

// @lc code=end
